package xyz.ibenben.zhongdian.system.service.impl;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;
import xyz.ibenben.zhongdian.common.annotation.SystemServiceLog;
import xyz.ibenben.zhongdian.common.constants.Constants;
import xyz.ibenben.zhongdian.system.dao.InnerMailRecordDao;
import xyz.ibenben.zhongdian.system.entity.InnerMailRecord;
import xyz.ibenben.zhongdian.system.service.InnerMailRecordService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * 站内信服务实现类
 * 提供了一些基本的服务，如根据公告Id和用户主键查找记录、
 * 根据用户获取未读消息数量、根据站内信主键删除记录等方法.
 * 主要用于用户之间通信使用此类来维护
 *
 * @author chenjian
 * @since 2017年9月27日上午10:57:28
 */
@Service("innerMailRecordService")
public class InnerMailRecordServiceImpl extends AbstractServiceImpl<InnerMailRecord> implements InnerMailRecordService {
    @Resource
    private InnerMailRecordDao innerMailRecordDao;

    @Transactional(rollbackFor = Exception.class)
    @Override
    @SystemServiceLog(description = "deleteByInnerMailKey站内信记录")
    public int deleteByInnerMailKey(Object key, HttpServletRequest request) {
        int result = 0;
        //获取条件imId = key的所有记录列表
        List<InnerMailRecord> list = innerMailRecordDao.selectByExample(getExample(key, null));
        if (list != null && !list.isEmpty()) {
            //逻辑删除
            InnerMailRecord entity = list.get(0);
            entity.setDelFlag(0);
            entity.setDelId((Long) request.getSession().getAttribute(Constants.SESSIONID));
            entity.setDelTime(new Date());
            result = this.updateAll(entity, request);
        }
        return result;
    }

    @Override
    @SystemServiceLog(description = "selectByMailIdAndUserId站内信记录")
    public InnerMailRecord selectByMailIdAndUserId(Long id, Long userId) {
        //通过发送者和接收者获取记录
        List<InnerMailRecord> list = innerMailRecordDao.selectByExample(getExample(userId, id));
        if (list != null && !list.isEmpty()) {
            return list.get(0);
        }
        return null;
    }

    /**
     * 获取条件实例
     *
     * @param toId 接收者
     * @param imId 发送者
     * @return 条件实例
     */
    private Example getExample(Object toId, Long imId) {
        Example example = new Example(InnerMailRecord.class);
        Criteria criteria = example.createCriteria();
        //接收者
        if (toId != null) {
            criteria.andEqualTo("toId", toId);
        }
        //发送者
        if (imId != null) {
            criteria.andEqualTo("imId", imId);
        }
        return example;
    }

}
